<template>
  <el-input
    v-model="currValue"
    v-bind="options"
    :type="type"
    :style="[
      !border ? '--el-input-border-color: transparent;' : '',
      backgroundColor ? '--el-input-bg-color: ' + backgroundColor : '',
    ]"
  >
    <template #prefix>
      <cc-icon v-if="prefixIconId" :iconId="prefixIconId" />
    </template>
    <template #suffix>
      <cc-icon v-if="suffixIconId" :iconId="suffixIconId" />
    </template>
  </el-input>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const currValue = ref('');
const type = ref('text');
const border = ref(false);
const backgroundColor = ref('');
const prefixIconId = ref('');
const suffixIconId = ref('');

const init = () => {
  const compStyle = props.compStyle;
  type.value = compStyle['hidden'] ? 'hidden' : 'text';
  border.value = compStyle['border'] !== false;
  backgroundColor.value = compStyle['background-color'] || '';
  prefixIconId.value = compStyle['prefixIcon'] || '';
  suffixIconId.value = compStyle['suffixIcon'] || '';

  if (!props.compData?.dataSourceType) {
    loadValue();
  }
};

const options = computed(() => {
  const compStyle = props.compStyle || {};
  const data = {};
  visual.addIfNotNull(data, compStyle, 'size');
  visual.addIfNotNull(data, compStyle, 'minlength');
  visual.addIfNotNull(data, compStyle, 'maxlength');
  visual.addIfNotNull(data, compStyle, 'placeholder');
  visual.addIfNotNull(data, compStyle, 'required');
  visual.addIfNotNull(data, compStyle, 'clearable');
  visual.addIfNotNull(data, compStyle, 'readonly');
  visual.addIfNotNull(data, compStyle, 'disabled');
  visual.addIfNotNull(data, compStyle, 'showWordLimit');
  visual.addIfNotNull(data, compStyle, 'autocomplete');
  return data;
});

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  currValue.value = dataList.length > 0 && dataList[0]['内容'] || '';
};

watch(() => props.compStyle, () => {
  init();
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  init();
  loadValue();
});
</script>